package com.ts.ischool.ui.ctrl;

import java.io.InputStreamReader;
import java.util.Date;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONObject;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.select.SelectorComposer;

import com.ts.ischool.pojo.UserBean;
import com.ts.ischool.service.UserService;

public class LoginController extends SelectorComposer<Component> {
	
	private static final String GOOGLECALENDARURL = "https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=";

	/**
	 * 
	 */
	private static final long serialVersionUID = -1275930739786290464L;
	
	private UserService userService;
	
	public void doAfterCompose(Component comp) throws Exception {
		super.doAfterCompose(comp);
		comp.setAttribute("controller", this);
		String loginName = Executions.getCurrent().getParameter("state");
		String access_token = Executions.getCurrent().getParameter("access_token");
		HttpClient httpclient = new DefaultHttpClient();
		HttpGet httpget = new HttpGet(GOOGLECALENDARURL + access_token);
		HttpResponse response = httpclient.execute(httpget);
		HttpEntity resEntity = response.getEntity();
		InputStreamReader reader = new InputStreamReader(
				resEntity.getContent(), "UTF-8");
		char[] buff = new char[1024];
		StringBuffer sb = new StringBuffer();
		int length = 0;
		while ((length = reader.read(buff)) != -1) {
			sb.append(new String(buff, 0, length));
		}
		JSONObject jsonobject = new JSONObject(sb.toString());
		UserBean user = userService.findUserByLoginName(loginName);
		UserBean userBean = new UserBean();
		String clientIp = Executions.getCurrent().getRemoteHost();
		userBean.setId(user.getId());
		if (jsonobject.isNull("error")) {
			userBean.setPassword(access_token);
			userBean.setUpdateDt(new Date());
			userBean.setLastLoginDt(new Date());
			userBean.setLastLoginIp(clientIp);
			userService.updateUser(userBean);
			Executions.getCurrent().getSession().setAttribute("loginUserInfo", user);
			Executions.sendRedirect("/index.zul");
		} else {
			Executions.sendRedirect("/welcome.zul");
		}
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}
}
